<template>
  <!-- 展示区域 -->
  <div class="home card mt20">
    <div v-for="(item, index) in showArr" :key="index" class="showAreaItem">
      <el-input :value="item" style="width: 50%" disabled />
      <el-button class="ml10" type="primary" @click="copyToClipboard(item, index)">复制并删除</el-button>
    </div>
    <div class="mt20" v-if="continuousUploadCount > 0">
      <span>Number of consecutive uploaded files</span>
      <el-input v-model="continuousUploadCount" class="mt10" style="width: 100%" disabled />
    </div>
    <div class="mt20" v-if="continuousUploadFileSize > 0">
      <span>Total file size: (Gb)</span>
      <el-input v-model="continuousUploadFileSize" class="mt10" style="width: 100%" disabled />
    </div>
    <el-button class="mt20" type="danger" @click="clearArrContent">clear All</el-button>
  </div>
  <!-- 模块一：教学软件上传 -->
  <div class="home card mt20">
    <div>
      <h3>educational software</h3>
      <div class="mt20" style="display: flex; align-items: center">
        <span>user/password：</span>
        <el-select v-model="userNameId" placeholder="Select" style="width: 240px" @change="changeAccount">
          <el-option v-for="item in userNameOptions" :key="item.value" :label="item.userName" :value="item.value">
            <span style="float: left">{{ item.userName }}</span>
            <span style="float: right; font-size: 13px; color: var(--el-text-color-secondary)">
              {{ item.password }}
            </span>
          </el-option>
        </el-select>
        <span class="ml20">token:</span>
        <el-input v-model="accessToken" class="ml10" style="width: 240px" disabled />
        <el-button type="success" style="margin-left: 20px" @click="() => initFn()">login in</el-button>
        <el-upload
          v-model:file-list="fileList"
          action="#"
          multiple
          class="ml20"
          style="display: flex; align-items: center"
          :http-request="uploadFunction"
        >
          <el-button type="primary">upload files</el-button>
        </el-upload>
      </div>
    </div>
  </div>
  <!-- 模块一：教学软件上传---连续上传 -->
  <div class="home card mt20">
    <div>
      <h3>educational software--Continuous Upload</h3>
      <div class="mt20" style="display: flex; align-items: center">
        <span>user/password：</span>
        <el-select v-model="userNameId" placeholder="Select" style="width: 240px" @change="changeAccount">
          <el-option v-for="item in userNameOptions" :key="item.value" :label="item.userName" :value="item.value">
            <span style="float: left">{{ item.userName }}</span>
            <span style="float: right; font-size: 13px; color: var(--el-text-color-secondary)">
              {{ item.password }}
            </span>
          </el-option>
        </el-select>
        <span class="ml20">token:</span>
        <el-input v-model="accessToken" class="ml10" style="width: 240px" disabled />
        <span class="ml20">upload frequency:</span>
        <el-input v-model="count" class="ml10" style="width: 240px" type="number" />
        <span class="ml20">s</span>
        <el-button type="success" style="margin-left: 20px" @click="() => initFn()">login in</el-button>
        <el-upload
          v-model:file-list="fileList"
          action="#"
          multiple
          class="ml20"
          style="display: flex; align-items: center"
          :http-request="uploadFunction_zero"
        >
          <el-button type="primary">upload files</el-button>
        </el-upload>
      </div>
    </div>
  </div>
  <!-- 模块二：充电桩 -->
  <div class="home card mt20">
    <div>
      <h3>Charging Station 2.0</h3>
      <div class="mt20" style="display: flex; align-items: center">
        <span>user/password：</span>
        <el-select v-model="userNameId2" placeholder="Select" style="width: 240px" @change="changeAccount2">
          <el-option v-for="item in userNameOptions2" :key="item.value" :label="item.userName" :value="item.value">
            <span style="float: left">{{ item.userName }}</span>
            <span style="float: right; font-size: 13px; color: var(--el-text-color-secondary)">
              {{ item.password }}
            </span>
          </el-option>
        </el-select>
        <span class="ml20">token:</span>
        <el-input v-model="accessToken2" class="ml10" style="width: 240px" disabled />
        <el-button type="success" style="margin-left: 20px" @click="() => initFn2()">login in</el-button>
        <el-upload
          v-model:file-list="fileList2"
          action="#"
          multiple
          class="ml20"
          style="display: flex; align-items: center"
          :http-request="uploadFunction2"
        >
          <el-button type="primary">upload files</el-button>
        </el-upload>
      </div>
    </div>
  </div>
  <!-- 充电桩持续上传 -->
  <div class="home card mt20">
    <div>
      <h3>Charging Station 2.0--Continuous Upload</h3>
      <div class="mt20" style="display: flex; align-items: center">
        <span>user/password：</span>
        <el-select v-model="userNameId2" placeholder="Select" style="width: 240px" @change="changeAccount2">
          <el-option v-for="item in userNameOptions2" :key="item.value" :label="item.userName" :value="item.value">
            <span style="float: left">{{ item.userName }}</span>
            <span style="float: right; font-size: 13px; color: var(--el-text-color-secondary)">
              {{ item.password }}
            </span>
          </el-option>
        </el-select>
        <span class="ml20">token:</span>
        <el-input v-model="accessToken2" class="ml10" style="width: 240px" disabled />
        <el-button type="success" style="margin-left: 20px" @click="() => initFn2()">login in</el-button>
        <el-upload
          v-model:file-list="fileList2"
          action="#"
          multiple
          class="ml20"
          style="display: flex; align-items: center"
          :http-request="uploadFunction2_continuous"
        >
          <el-button type="primary">upload files</el-button>
        </el-upload>
      </div>
    </div>
  </div>
  <!-- 上传到我自己的OSS -->
  <div class="home card mt20">
    <div>
      <h3>target management</h3>
      <div class="mt20" style="display: flex; align-items: center">
        <span>user/password：</span>
        <el-select v-model="userNameId3" placeholder="Select" style="width: 240px" @change="changeAccount3">
          <el-option v-for="item in userNameOptions3" :key="item.value" :label="item.userName" :value="item.value">
            <span style="float: left">{{ item.userName }}</span>
            <span style="float: right; font-size: 13px; color: var(--el-text-color-secondary)">
              {{ item.password }}
            </span>
          </el-option>
        </el-select>
        <span class="ml20">token:</span>
        <el-input v-model="accessToken3" class="ml10" style="width: 240px" disabled />
        <el-select v-model="targetValue" placeholder="请选择" style="width: 240px" class="ml10">
          <el-option v-for="item in targetOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-select v-model="stepValue" placeholder="请选择阶段" style="width: 240px" class="ml10">
          <el-option v-for="item in stepOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-input v-model="nowDate" style="width: 240px" class="ml10" disabled />
        <el-button type="success" style="margin-left: 20px" @click="() => initFn3()">login in</el-button>
        <el-upload
          v-model:file-list="fileList3"
          action="#"
          multiple
          class="ml20"
          style="display: flex; align-items: center"
          :http-request="uploadFunction3"
        >
          <el-button type="primary">upload files</el-button>
        </el-upload>
      </div>
    </div>
  </div>
  <!-- 上传到码云仓库 -->
</template>

<script setup lang="ts" name="home">
import { ref, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";
// import { useGlobalStore } from "@/stores/modules/global";
// import { storeToRefs } from "pinia";
import { v4 as uuidv4 } from "uuid";

const showArr = ref<string[]>([]);
// const globalStore = useGlobalStore();
// const { UUID } = storeToRefs(globalStore);
const fileList = ref([]);
const fileList2 = ref([]);
const fileList3 = ref([]);
const link = ref("");
const link2 = ref("");
const link3 = ref("");
const accessToken = ref<any>("");
const accessToken2 = ref("");
const userNameId = ref("0");
const userNameId2 = ref("0");
const userNameId3 = ref("0");
const userNameOptions = ref([
  {
    value: "0",
    userName: "xie66",
    password: "admin123"
  },
  {
    value: "1",
    userName: "admin5",
    password: "admin123"
  }
]);
const userNameOptions2 = ref([
  {
    value: "0",
    userName: "admin",
    password: "admin123"
  }
]);
const userNameOptions3 = ref([
  {
    value: "0",
    userName: "axie",
    password: "xiequantai1996"
  }
]);
const targetValue = ref("");
const targetOptions = ref<
  Array<{
    value: string;
    label: string;
  }>
>([]);
const stepValue = ref("");
const stepOptions = ref([
  {
    value: "第一阶段/",
    label: "第一阶段/"
  }
]);
const nowDate = ref("");
const storageValue = ref("");
const accessToken3 = ref("");
const serverObject = ref<{
  accessKeyId: string;
  accessKeySecret: string;
  stsToken: string;
}>({
  accessKeyId: "",
  accessKeySecret: "",
  stsToken: ""
});
const service = axios.create({
  baseURL: "http://58.251.5.22:32757",
  timeout: 50000,
  headers: {
    "tenant-id": "1"
  }
});
const service2 = axios.create({
  baseURL: "https://charging-api-sit.guiwanpark.com",
  timeout: 50000,
  headers: {
    "tenant-id": "1"
  }
});
const myAliCloudService = axios.create({
  baseURL: "http://47.120.28.21:3000",
  timeout: 50000,
  headers: {
    "tenant-id": "1"
  }
});
/**
 * please求拦截器
 */
service.interceptors.request.use(config => {
  if (accessToken.value) {
    config.headers.Authorization = `Bearer ${accessToken.value}`;
  }
  return config;
});
service2.interceptors.request.use(config => {
  if (accessToken2.value) {
    config.headers["Content-Type"] = "multipart/form-data";
    config.headers.Authorization = `Bearer ${accessToken2.value}`;
  }
  return config;
});
myAliCloudService.interceptors.request.use(config => {
  if (accessToken3.value) {
    config.headers["Content-Type"] = "multipart/form-data";
    config.headers.Authorization = `Bearer ${accessToken3.value}`;
  }
  return config;
});
const initFn = async () => {
  /**
   * 1.登录，获取token
   * 2.根据拿到的token换区OSS的STS Token
   */
  accessToken.value = await login();
  const ossObjRes = await getOssToken();
  serverObject.value = {
    accessKeyId: ossObjRes.data.data.accessKeyId,
    accessKeySecret: ossObjRes.data.data.accessKeySecret,
    stsToken: ossObjRes.data.data.token
  };
};
const initFn2 = async () => {
  accessToken2.value = await login2();
};
const initFn3 = async () => {
  accessToken3.value = await login3();
  getTargetFolders();
};
function getFormattedDate() {
  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth() + 1; // 月份从0开始需+1
  const day = now.getDate();

  return `${year}年${month}月${day}日/`;
}
const getTargetFolders = async () => {
  const res = await myAliCloudService.get("/getFolders");
  targetOptions.value = res.data.data.map(item => ({
    value: item,
    label: item
  }));
};
const changeAccount = async () => {
  await initFn();
};
const changeAccount2 = async () => {
  await initFn2();
};
const changeAccount3 = async () => {
  await initFn();
};
const login = async () => {
  const res = await service.post("/admin-api/system/auth/login", {
    captchaVerification: "",
    loginType: "2",
    rememberMe: false,
    tenantName: "芋道源码",
    username: userNameOptions.value.find(item => item.value == userNameId.value)?.userName,
    password: userNameOptions.value.find(item => item.value == userNameId.value)?.password
  });
  return res.data.data.accessToken;
};
const login2 = async () => {
  const res = await service2.post("/admin-api/system/auth/login", {
    tenantName: "1165",
    captchaVerification: "",
    rememberMe: false,
    loginType: 2,
    username: userNameOptions2.value.find(item => item.value == userNameId2.value)?.userName,
    password: userNameOptions2.value.find(item => item.value == userNameId2.value)?.password
  });
  return res.data.data.accessToken;
};
const login3 = async () => {
  const res = await myAliCloudService.post("/upload/login", {
    username: userNameOptions3.value.find(item => item.value == userNameId3.value)?.userName,
    password: userNameOptions3.value.find(item => item.value == userNameId3.value)?.password
  });
  return res.data.token;
};
onMounted(() => {
  nowDate.value = getFormattedDate();
});
const getOssToken = async () => {
  const res = await service.get("/admin-api/edu/file/getToken");
  return res;
};
// const beforeAvatarUpload2 = rawFile => {
//   const whiteList = ["image/png", "image/jpeg", "image/jpg"];
//   if (!whiteList.includes(rawFile.type)) {
//     ElMessage.error("只支持图片类型文件");
//   }
//   return whiteList.includes(rawFile.type);
// };
const uploadFunction = async fileObj => {
  const client = new OSS({
    region: "oss-cn-shenzhen",
    accessKeyId: serverObject.value.accessKeyId,
    accessKeySecret: serverObject.value.accessKeySecret,
    stsToken: serverObject.value.stsToken,
    bucket: "educt-files"
  });

  const fileNameArr = fileObj.file.name.split(".");
  const name = uuidv4() + "." + fileNameArr[fileNameArr.length - 1];
  const options = {
    meta: { temp: "demo" },
    mime: "json",
    headers: {
      "Cache-Control": "no-cache",
      "Content-Encoding": "utf-8",
      "Access-Control-Allow-Origin": "*",
      "x-oss-forbid-overwrite": "false",
      "Content-Type": "application/x-www-form-urlencoded"
    }
  };
  const result = await client.put(name, fileObj.file, options);
  link.value = result.url.replace("http:", "https:");
  showArr.value.push(link.value);
};
// 循环次数
const count = ref(0.5);
// 连续上传成功次数
const continuousUploadCount = ref(0);
// 单个文件大小
const simpleFileSize = ref();
// 文件大小
const continuousUploadFileSize = computed(() => {
  return (continuousUploadCount.value * simpleFileSize.value) / (1024 * 1024 * 1024);
});
const uploadFunction_zero = async fileObj => {
  setInterval(
    async () => {
      // 1.获取token
      accessToken.value = await login();
      // 2.获取STS
      const ossObjRes = await getOssToken();
      serverObject.value = {
        accessKeyId: ossObjRes.data.data.accessKeyId,
        accessKeySecret: ossObjRes.data.data.accessKeySecret,
        stsToken: ossObjRes.data.data.token
      };
    },
    1000 * 60 * 10
  );
  setInterval(async () => {
    // 3.配置OSS
    const client = new OSS({
      region: "oss-cn-shenzhen",
      accessKeyId: serverObject.value.accessKeyId,
      accessKeySecret: serverObject.value.accessKeySecret,
      stsToken: serverObject.value.stsToken,
      bucket: "educt-files"
    });
    const fileNameArr = fileObj.file.name.split(".");
    const options = {
      meta: { temp: "demo" },
      mime: "json",
      headers: {
        "Cache-Control": "no-cache",
        "Content-Encoding": "utf-8",
        "Access-Control-Allow-Origin": "*",
        "x-oss-forbid-overwrite": "false",
        "Content-Type": "application/x-www-form-urlencoded"
      }
    };
    const name = uuidv4() + "." + fileNameArr[fileNameArr.length - 1];
    try {
      const result = await client.put(name, fileObj.file, options);
      simpleFileSize.value = fileObj.file.size;

      link.value = result.url.replace("http:", "https:");
      showArr.value = [link.value];
      continuousUploadCount.value++;
    } catch (error) {
      console.log(error);
    }
  }, 1000 * count.value);
};
const uploadFunction2 = async fileParam => {
  const res = await service2.post("/admin-api/infra/file/upload", {
    file: fileParam.file
  });
  link2.value = res.data.data;
  showArr.value.push(link2.value);
};
const uploadFunction2_continuous = fileParam => {
  setInterval(async () => {
    const res = await service2.post("/admin-api/infra/file/upload", {
      file: fileParam.file
    });
    link2.value = res.data.data;
    showArr.value.push(link2.value);
  }, 1000);
};
const uploadFunction3 = async fileParam => {
  if (targetValue.value && stepValue.value) {
    const res = await myAliCloudService.post("/uploadFile", {
      file: fileParam.file,
      folder: targetValue.value + stepValue.value + nowDate.value
    });
    link3.value = res.data.url;
    showArr.value.push(link3.value);
  } else {
    fileList3.value = [];
    ElMessage.warning("选择文件夹");
  }
};
/**
 * 复制链接
 */
async function copyToClipboard(text, _index) {
  if (text) {
    if (navigator.clipboard) {
      try {
        await navigator.clipboard.writeText(text);
        ElMessage.success("已复制到剪贴板");
        showArr.value.splice(_index, 1);
      } catch (err) {
        ElMessage.error("操作失败");
        throw new Error(JSON.stringify(err));
      }
    } else {
      // 创建隐藏的textarea元素
      const textarea = document.createElement("textarea");
      textarea.value = text; // 设置要复制的文本
      textarea.style.position = "absolute"; // 隐藏textarea
      textarea.style.left = "-9999px";

      document.body.appendChild(textarea); // 添加到DOM

      // 选中textarea的内容
      textarea.select();
      textarea.setSelectionRange(0, 99999); // 适应不同浏览器，尽量选中所有内容

      // 尝试执行复制命令
      try {
        const success = document.execCommand("copy");
        if (success) {
          ElMessage.success("已复制到剪贴板");
        } else {
          ElMessage.error("操作失败");
        }
      } catch (err) {
        ElMessage.error("操作失败" + JSON.stringify(err));
      }

      // 清理，移除临时创建的textarea
      document.body.removeChild(textarea);
      showArr.value.splice(_index, 1);
    }
  } else {
    ElMessage.warning("不要复制空文本");
  }
}
const clearArrContent = () => {
  showArr.value = [];
  /**
   * 第一模块：教学软件
   */
  link.value = "";
  fileList.value = [];
  /**
   * 第二模块：充电桩2.0版本
   */
  link2.value = "";
  fileList2.value = [];
  /**
   * 第三模块：目标管理
   */
  fileList3.value = [];
  storageValue.value = "";
};
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
